<script setup lang="ts">
import type { SysTenantReq, SysTenantResp } from '#/type/sys_tenant';

import { onBeforeMount, reactive, ref, toRaw } from 'vue';

import {
  Button,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Popconfirm,
  RangePicker,
  Row,
  Select,
  SelectOption,
  Table,
} from 'ant-design-vue';

import { createEditTenantApi, deleteTenantApi, getTenantPageApi } from '#/api';

import ModalBox from './modalBox.vue';
import useFormHook from './useFormHook';
import useTableHook from './useTableHook';
// 设置组件 name
defineOptions({
  name: 'SysTenant',
});
// ------------------ 表单数据 ----------------------
const formSearch = reactive<SysTenantReq>({});
// ------------------ 表格数据 ----------------------
// 分页参数
const tablePagination = reactive<Record<string, any>>({
  total: 0,
  current: 1,
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  showSizeChanger: true,
  showQuickJumper: true,
  sorter: null,
});
// 表格数据
const tableData = ref<SysTenantResp[]>([]);

// 获取表格数据
const fetchTenantPageData = (search: SysTenantReq) => {
  getTenantPageApi(search).then((res) => {
    tableData.value = res.data as SysTenantResp[];
    tablePagination.total = res.total as number;
  });
};

const fetchTableData = () => {
  fetchTenantPageData({ ...toRaw(formSearch), ...toRaw(tablePagination) });
};

// fetchTableData(params)
// ------------------ 其他数据 ----------------------
const modalOpen = ref(false);
const modalData = ref<SysTenantResp>({});

const saveTenant = (entity: SysTenantResp) => {
  createEditTenantApi(entity).then(() => {
    fetchTableData();
    modalOpen.value = false;
    message.success('成功');
  });
};
const deleteTenant = (ids: Array<string>) => {
  deleteTenantApi(ids).then(() => {
    fetchTableData();
    message.success('成功');
  });
};

const { tableColumns, tableChange } = useTableHook(
  fetchTableData,
  tablePagination,
);
const {
  formSearchSubmit,
  formSearchReset,
  formInputClear,
  formSelectClear,
  formDateRangeClear,
} = useFormHook(fetchTableData, formSearch, tablePagination);

// 生命周期函数，获取数据
onBeforeMount(() => {
  fetchTableData();
});

const modalBoxShow = (record: null | SysTenantResp = {}) => {
  modalData.value = record || ({} as SysTenantResp);
  modalOpen.value = true;
};
const modalBoxSubmit = (entity: SysTenantResp) => {
  saveTenant(entity);
};
const tableRecordDelete = (record: SysTenantResp) => {
  deleteTenant([record.tenant_id as string]);
};
</script>

<template>
  <div>
    <Row>
      <Col :span="24" class="mx-5 mt-4 h-12 w-full">
        <Form class="flex justify-start" layout="inline">
          <FormItem label="租户名称">
            <Input
              v-model:value="formSearch.tenant_name"
              allow-clear
              placeholder="请输入租户名称"
              @change="formInputClear('role_name', $event)"
            />
          </FormItem>
          <FormItem label="企业名称">
            <Input
              v-model:value="formSearch.org_name"
              allow-clear
              placeholder="请输入企业名称"
              @change="formInputClear('role_code', $event)"
            />
          </FormItem>
          <FormItem label="状态">
            <Select
              v-model:value="formSearch.status"
              allow-clear
              placeholder="请选择状态"
              @change="formSelectClear('status', $event)"
            >
              <SelectOption :value="1">正常</SelectOption>
              <SelectOption :value="0">禁用</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="创建时间">
            <RangePicker
              v-model:value="formSearch.create_time_range"
              allow-clear
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="
                (dates, dateStrings) =>
                  formDateRangeClear('create_time_range', dates, dateStrings)
              "
            />
          </FormItem>
          <FormItem class="flex justify-around">
            <Button class="bg-blue-500" @click="formSearchSubmit">查询</Button>
            <Button class="bg-gray-300" @click="formSearchReset">重置</Button>
            <Button class="bg-red-300" @click="modalBoxShow(null)">新建</Button>
          </FormItem>
        </Form>
      </Col>
    </Row>
    <Row class="mx-5 h-full">
      <Col :span="24" class="h-full">
        <Table
          :columns="tableColumns"
          :data-source="tableData"
          :pagination="tablePagination"
          @change="tableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'operation'">
              <div class="flex justify-evenly">
                <Button type="text" @click="modalBoxShow(record)">编辑</Button>
                <Popconfirm
                  cancel-text="取消"
                  ok-text="确定"
                  title="确定删除吗？"
                  @confirm="() => tableRecordDelete(record)"
                >
                  <Button danger type="text">删除</Button>
                </Popconfirm>
              </div>
            </template>
          </template>
        </Table>
      </Col>
    </Row>
    <ModalBox
      :data="modalData"
      :open="modalOpen"
      @cancel="modalOpen = false"
      @ok="modalBoxSubmit"
    />
  </div>
</template>

<style scoped></style>
